package zh.dummy.netty.core.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import zh.dummy.netty.core.exception.NettyRequestNullException;
import zh.dummy.netty.core.protocol.NettyMessage;

public class NettyMessageEncoder extends MessageToByteEncoder<NettyMessage>{

	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	
	private FastjsonEncoder fastjsonEncoder;
	
	public NettyMessageEncoder(){
		this.fastjsonEncoder = new FastjsonEncoder();
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf out) throws Exception {
		if(msg == null || msg.getHeader() == null){
			throw new NettyRequestNullException("netty request is null");
		}
		if(logger.isDebugEnabled()){
			logger.debug("Encode NettyMessage : {}",msg.toString());
		}
		
		out.writeInt(msg.getHeader().getCrcCode());
		out.writeLong(msg.getHeader().getSessionID());
		out.writeByte(msg.getHeader().getType());
		out.writeByte(msg.getHeader().getPriority());
		fastjsonEncoder.encodeHeaderAttch(msg.getHeader().getAttchment(), out);
		if(msg.getBody() != null){
			fastjsonEncoder.encodeBody(msg.getBody(), out);
		}
	}

}
